#include<bits/stdc++.h>
using namespace std;
#define ll long long
ll T,a,b,n;

int main(){
	scanf("%lld",&T);
	while(T--){
		scanf("%lld%lld%lld",&a,&b,&n);
		ll ans=1e18;
		for(int i=1;i<=100;i++){
			for(int j=1;j<=100;j++){
				if(i==1&&j==1) continue;
				if((b*j-a*i-b+a+n)%n==0)
					ans=min(ans,(ll)(i-1)*(i-1)+(j-1)*(j-1));
			}
		}
		printf("%lld\n",ans);
	}
	return 0;
}
